<template>
  <div class="plan-pane" style="height: 66vh">
    <!-- 工具条 -->
    <!-- 工具条：紧凑版 -->
    <div class="toolbar toolbar--compact">
      <div class="left">
        <el-input
          v-model="q.keyword"
          size="small"
          placeholder="计划内容搜索"
          clearable
          style="width: 200px"
          @keyup.enter="fetchList"
          @clear="fetchList"
        >
          <template #prefix
            ><el-icon><Search /></el-icon
          ></template>
        </el-input>

        <SingleDateRange
          v-model="q.dateRange"
          @normalized="onNorm"
          @change="fetchList"
          placeholder="计划日期范围选择"
          style="width: 400px"
        />
        <!-- <el-date-picker
          v-model="q.dateRange"
          size="small"
          type="daterange"
          range-separator="~"
          start-placeholder="计划开始日期"
          end-placeholder="计划结束日期"
          value-format="YYYY-MM-DD"
          unlink-panels
          @change="fetchList"
        /> -->
      </div>

      <div class="right">
        <el-button type="primary" :icon="Search" @click="fetchList"
          >查询</el-button
        >
        <el-button :icon="Refresh" @click="resetAndSearch">重置</el-button>
        <el-button
          size="small"
          type="primary"
          @click="openAddPlan(props.row)"
          :disabled="!row?.id"
        >
          <el-icon><Plus /></el-icon>新增计划
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-scroll">
      <el-table
        v-loading="loading"
        :data="rows"
        border
        stripe
        :height="tableHeight"
        class="plan-table wide-table"
        :header-cell-style="headerCellStyle"
        :cell-style="cellStyle"
      >
        <!-- <el-table-column type="index" label="#" width="56" align="center" /> -->

        <el-table-column
          prop="planDate"
          label="计划日期"
          width="160"
          sortable
          :sort-method="(a, b) => dateSort(a.planDate, b.planDate)"
        >
          <template #default="{ row }">{{ row.planDate }}</template>
        </el-table-column>

        <!-- <el-table-column label="设备名称" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">{{ row.assetName || "-" }}</template>
        </el-table-column> -->

        <!-- <el-table-column prop="title" label="标题" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">{{ row.title || '-' }}</template>
        </el-table-column> -->

        

        <el-table-column label="计划标题" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">{{ row.title || "-" }}</template>
        </el-table-column>

        <el-table-column label="计划内容" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">{{ row.planContent || "-" }}</template>
        </el-table-column>

        <el-table-column label="计划工时" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">{{ row.planHour + " 小时 " || "-" }}</template>
        </el-table-column>
        <el-table-column label="维护工种" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">{{ row.tradeCode || "-" }}</template>
        </el-table-column>

        <el-table-column label="备件信息" header-align="center" align="center">
          <!-- 备件名称 -->
          <el-table-column label="需用备件名称" min-width="180" align="left">
            <template #default="{ row }">
              <div
                v-if="Array.isArray(row.spareInfos) && row.spareInfos.length"
                class="stack"
              >
                <div
                  v-for="(sp, i) in row.spareInfos"
                  :key="sp.id ?? sp.code ?? i"
                  class="line one-line"
                >
                  <el-tooltip
                    :content="
                      sp.code ? `${sp.name}（${sp.code}）` : sp.name ?? '-'
                    "
                    placement="top"
                  >
                    <span>{{ sp.name || "-" }}</span>
                  </el-tooltip>
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column label="需用备件数量" min-width="180" align="center">
            <template #default="{ row }">
              <div
                v-if="Array.isArray(row.spareInfos) && row.spareInfos.length"
                class="stack num-col"
              >
                <div
                  v-for="(sp, i) in row.spareInfos"
                  :key="sp.id ?? sp.code ?? i"
                  class="line one-line"
                >
                  <el-tooltip
                    :content="
                      sp.code ? `${sp.name}（${sp.code}）` : sp.name ?? '-'
                    "
                    placement="top"
                  >
                    <span>{{ sp.qty || "-" }}</span>
                  </el-tooltip>
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <el-table-column label="需用备件类型" min-width="180" align="center">
            <template #default="{ row }">
              <div
                v-if="Array.isArray(row.spareInfos) && row.spareInfos.length"
                class="stack num-col"
              >
                <div
                  v-for="(sp, i) in row.spareInfos"
                  :key="sp.id ?? sp.code ?? i"
                  class="line one-line"
                >
                  <el-tooltip
                    :content="
                      sp.type ? `${sp.name}（${sp.code}）` : sp.type ?? '-'
                    "
                    placement="top"
                  >
                    <el-tag
                      size="small"
                      :type="(sp.type ?? 0) === 1 ? 'warning' : 'success'"
                    >
                      {{ (sp.type ?? 0) === 1 ? "特殊" : "普通" }}
                    </el-tag>
                  </el-tooltip>
                </div>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="总库存" width="100" align="center">
    <template #default="{ row }">
      <div v-if="Array.isArray(row.spareInfos) && row.spareInfos.length" class="stack num-col">
        <div v-for="(sp, i) in row.spareInfos" :key="sp.id ?? sp.code ?? i" class="line">
          {{ sp?.stockTotal ?? '-' }}
        </div>
      </div>
      <span v-else>-</span>
    </template>
  </el-table-column>

   
  <el-table-column label="当前库存" width="100" align="center">
    <template #default="{ row }">
      <div v-if="Array.isArray(row.spareInfos) && row.spareInfos.length" class="stack num-col">
        <div v-for="(sp, i) in row.spareInfos" :key="sp.id ?? sp.code ?? i" class="line">
          {{ sp?.stockAvailable ?? '-' }}
        </div>
      </div>
      <span v-else>-</span>
    </template>
  </el-table-column>

  
  <el-table-column label="已用数量" width="100" align="center">
    <template #default="{ row }">
      <div v-if="Array.isArray(row.spareInfos) && row.spareInfos.length" class="stack num-col">
        <div v-for="(sp, i) in row.spareInfos" :key="sp.id ?? sp.code ?? i" class="line">
          {{
            (sp?.stockTotal ?? null) !== null && (sp?.stockAvailable ?? null) !== null
              ? (Number(sp.stockTotal) - Number(sp.stockAvailable))
              : '-'
          }}
        </div>
      </div>
      <span v-else>-</span>
    </template>
  </el-table-column> -->
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          width="170"
          sortable
          :sort-method="(a, b) => dateSort(a.createTime, b.createTime)"
        >
          <template #default="{ row }">{{ row.createTime }}</template>
        </el-table-column>

        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="openEditPlan(row)"
              >编辑备件</el-button
            >
            <el-button link type="danger" size="small" @click="onRemove(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>

        <template #empty>
          <el-empty
            :description="row?.id ? '暂无计划数据' : '请选择左侧设备节点'"
          />
        </template>
      </el-table>
    </div>

    <!-- 分页 -->
    <!-- <div class="pager" v-if="total > 0">
      <el-pagination
        v-model:current-page="q.pageNum"
        v-model:page-size="q.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div> -->

    <el-pagination
      v-if="total > 0"
      class="wo-pager"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      v-model:current-page="q.pageNum"
      v-model:page-size="q.pageSize"
      @current-change="fetchList"
      @size-change="fetchList"
    />


    <EditPlanSparesDialog
      v-model="editSparesVisible"
      :plan="editingPlan"
      @success="fetchList"
    />
  </div>
  <PlanDialog
    v-model="addVisible"
    mode="create"
    :asset="addPlanAsset"
    @success="fetchList"
  />
  <PlanDialog
    v-model="editVisible"
    mode="edit"
    :plan="editingPlan"
    @success="fetchList"
  />
</template>

<script setup>
import { ref, watch, computed, reactive } from "vue";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { listMtplan, delMtplan } from "@/api/sbtz/mtplan";
import EditPlanSparesDialog from "@/components/sbtz/plan/EditPlanSparesDialog.vue";
import PlanDialog from "@/components/sbtz/plan/PlanDialog.vue";
import { ElMessageBox, ElMessage } from "element-plus";

const props = defineProps({
  row: { type: Object, default: () => ({}) },
  onAddPlan: { type: Function, default: null },
  height: { type: [Number, String], default: 480 },
  refreshTick: { type: [Number, String], default: 0 },
});
const emit = defineEmits(["view", "edit", "remove"]);

const editSparesVisible = ref(false);
const editingPlan = ref(null);

function openEditSpares(row) {
  editingPlan.value = row; // 需要包含 id、title
  editSparesVisible.value = true;
}

const addVisible = ref(false);
const editVisible = ref(false);
const addPlanAsset = ref(null);

function openAddPlan(row) {
  addPlanAsset.value = row;
  addVisible.value = true;
}
function openEditPlan(row) {
  editingPlan.value = row;
  console.log(row);
  editVisible.value = true;
}

async function onRemove(row) {
  try {
    await ElMessageBox.confirm(
      `确认删除计划「${row.title || row.id}」吗？`,
      "提示",
      {
        type: "warning",
        confirmButtonText: "删除",
        cancelButtonText: "取消",
      }
    );
    await delMtplan(row.id); // ✅ 单个 id
    ElMessage.success("删除成功");
    fetchList(); // 重新加载列表
  } catch (e) {
    // 用户取消或接口报错
  }
}

const rows = ref([]);
const total = ref(0);
const loading = ref(false);
const q = reactive({ keyword: "", dateRange: null, pageNum: 1, pageSize: 20 });

const tableHeight = computed(() => {
  const h = String(props.height);
  if (/^\d+$/.test(h)) return Number(h); // 给工具条/分页预留空间
  return null;
});

/** 映射后端行（用你的字段名） */
function adapt(r = {}) {
  return {
    id: r.id,
    assetId: r.assetId,
    assetName: r.assetName, // ← 后端 join 出来
    title: r.title,
    planContent: r.planContent,
    tradeCode: r.tradeCode,
    planDate: r.planDate,
    planType: r.planType,
    status: r.status,
    needSpare: Number(r.needSpare) === 1,
    createTime: r.createTime,
  };
}
/** 统一 rows 解析 */
function pickRows(res) {
  if (Array.isArray(res?.rows)) return res.rows;
  if (Array.isArray(res?.data?.rows)) return res.data.rows;
  if (Array.isArray(res?.data)) return res.data;
  if (Array.isArray(res)) return res;
  return [];
}

async function fetchList() {
  if (!props.row?.id) {
    rows.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    // 组织参数
    const params = {
      pageNum: q.pageNum,
      pageSize: q.pageSize,
      assetId: props.row?.id || null, // 《把设备ID放到同一个对象里》
      keyword: q.keyword || null,
      // 若依习惯用 params[beginTime]/params[endTime]
      "params[beginTime]": Array.isArray(q.dateRange) ? q.dateRange[0] : null,
      "params[endTime]": Array.isArray(q.dateRange) ? q.dateRange[1] : null,

      // const fmt = (d) => d ? dayjs(d).format('YYYY-MM-DD HH:mm:ss') : null;
      // beginTime = fmt(q.dateRange?.[0]);
      // endTime   = fmt(q.dateRange?.[1]);
      // dayjs(q.dateRange[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    };

    // 调用时只传一个对象
    const res = await listMtplan(params);
    console.log(res);
    const page = pickRows(res); // 当前页的计划数组（res.rows）
    rows.value = page.map(mapPlanRow);
    total.value = Number(res?.total ?? page.length);
  } finally {
    loading.value = false;
  }
}

function toNum(v) {
  const n = Number(v);
  return Number.isFinite(n) ? n : null;
}

function mapPlanRow(p) {
  return {
    ...p,
    spareInfos: Array.isArray(p.spares)
      ? p.spares.map((s) => {
          const stockTotal = toNum(s.stockTotal ?? s.stock_all ?? s.totalStock);
          const stockAvailable = toNum(
            s.stockAvailable ?? s.stock_now ?? s.currentStock
          );
          return {
            id: s.spareId,
            code: s.spareCode ?? s.code,
            name: s.spareName ?? s.name,
            qty: s.qty,
            type: s.spareType, 
            stockTotal: s.stockTotal,
            stockAvailable: s.stockAvailable,
            // 需要的话也可预计算已用
            used:
              s.stockTotal != null && s.stockAvailable != null
                ? s.stockTotal - s.stockAvailable
                : null,
          };
        })
      : [],
  };
}

function attachSpareList(p = {}) {
  const spares = Array.isArray(p.spares) ? p.spares : [];
  const spareList = spares.map((s) => ({
    id: s?.spareId ?? s?.id ?? null,
    code: s?.spareCode ?? s?.code ?? "",
    name: s?.spareName ?? s?.name ?? "",
    type: Number(s?.spareType ?? 0),
    qty: Number(s?.qty ?? 0),
    orderDate: s?.spareOrderDate ?? s?.orderDate ?? null,
    unit: s?.spare?.unit ?? s?.unit ?? "",
    stockNow: Number(s?.stockAvailable ?? s?.stockNow ?? 0),
    stockAll: Number(s?.stockTotal ?? s?.stockAll ?? 0),
    usedQty: Number(s?.usedQty ?? 0),
  }));
  return { ...p, spareList };
}

function expandPlansToRows(list = []) {
  const out = [];
  for (const p of list) {
    const base = {
      id: p.id,
      assetId: p.assetId,
      assetName: p.assetName,
      title: p.title,
      planContent: p.planContent,
      tradeCode: p.tradeCode,
      planDate: p.planDate,
      planType: p.planType,
      status: p.status,
      needSpare: Number(p.needSpare) === 1,
      createTime: p.createTime,
    };
    // 没有 spares 也保留一行
    const rels = Array.isArray(p.spares) && p.spares.length ? p.spares : [null];
    for (const s of rels) {
      out.push({
        ...base,
        spareId: s?.spareId ?? null,
        spareCode: s?.spareCode ?? s?.code ?? "",
        spareName: s?.spareName ?? s?.name ?? "",
        unit: s?.spare?.unit ?? s?.unit ?? "",
        spareType: Number(s?.spareType ?? 0),
        spareStatus: Number(s?.spareStatus ?? 0),
        qty: Number(s?.qty ?? 0),
        orderDate: s?.spareOrderDate ?? s?.orderDate ?? null,
      });
    }
  }
  return out;
}

function onNorm(range) {
  const toYmd = (d) =>
    typeof d === "string"
      ? d.slice(0, 10)
      : `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(d.getDate()).padStart(2, "0")}`;
  q.dateRange = Array.isArray(range) ? range.map(toYmd) : null;
}
function handleAdd() {
  // 优先调用父传入的 onAddPlan（openAddPlan），否则回退到 onAdd
  if (typeof props.onAddPlan === "function") return props.onAddPlan(props.row);
  if (typeof props.onAdd === "function") return props.onAdd(props.row);
}

/** 小工具 */
const dateSort = (a, b) =>
  (a ? new Date(a).getTime() : 0) - (b ? new Date(b).getTime() : 0);
function fmtDate(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  return `${y}-${m}-${D}`;
}
function fmtDateTime(d) {
  if (!d) return "-";
  const t = new Date(d);
  if (isNaN(t)) return "-";
  const y = t.getFullYear(),
    m = String(t.getMonth() + 1).padStart(2, "0"),
    D = String(t.getDate()).padStart(2, "0");
  const h = String(t.getHours()).padStart(2, "0"),
    mi = String(t.getMinutes()).padStart(2, "0");
  return `${y}-${m}-${D} ${h}:${mi}`;
}

watch(
  () => props.row?.id,
  () => {
    q.pageNum = 1;
    fetchList();
  },
  { immediate: true }
);
watch(
  () => props.refreshTick,
  () => {
    // 不改页码，只做刷新；如需回到第1页可在这里重置 pageNum
    fetchList();
  }
);

/** 表样式 */
const headerCellStyle = () => ({
  background: "linear-gradient(180deg, #fafafa, #f3f4f6)",
  color: "#344054",
  fontWeight: 700,
  borderColor: "#eef0f3",
});
const cellStyle = () => ({ color: "#1f2937", borderColor: "#f1f2f5" });
</script>

<style scoped>
.plan-pane {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 10px;
  padding: 10px 12px;
}
.toolbar .left {
  display: flex;
  gap: 10px;
  align-items: center;
}
.toolbar .right {
  display: flex;
  gap: 8px;
}
.plan-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.05);
}
.pager {
  display: flex;
  justify-content: flex-end;
}

/* 紧凑工具条（图1风格） */
.toolbar--compact {
  --ctl-h: 28px; /* 小号控件高度 */
  --ctl-fs: 12px; /* 小号字体 */
  padding: 6px 10px; /* 更紧的左右内边距 */
}
.toolbar--compact .left {
  gap: 8px;
}
.toolbar--compact .right {
  gap: 6px;
}

/* 统一控件尺寸与描边（Element Plus 用 box-shadow 作边框） */
.toolbar--compact :deep(.el-input__wrapper),
.toolbar--compact :deep(.el-select .el-select__wrapper),
.toolbar--compact :deep(.el-range-editor) {
  height: var(--ctl-h);
  font-size: var(--ctl-fs);
  padding: 0 8px;
}

/* 小号按钮 */
.toolbar--compact :deep(.el-button) {
  height: var(--ctl-h);
  padding: 0 10px;
  font-size: var(--ctl-fs);
}

/* 占位符更轻一些（可选） */
.toolbar--compact :deep(.el-input__inner::placeholder),
.toolbar--compact :deep(.el-range-editor__input::placeholder) {
  color: var(--el-text-color-placeholder);
}

/* 外层容器：允许水平/垂直滚动 */
.table-scroll {
  /* 高度占满可用空间，超出滚动 */ 
  overflow: auto; /* 同时支持横向&纵向滚动 */
}

/* 让 el-table 根据列宽“自然撑开”，从而产生横向滚动 */
.wide-table {
  width: max-content; /* 关键：按内容宽度展开 */
  min-width: 100%; /* 小于容器时至少占满容器 */
}

/* 保持你的原有美化 */
.plan-table {
  border-radius: 12px;
  overflow: hidden; /* 保留阴影圆角 */
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.05);
}

/* 统一用 el-table 的边框色 */
/* 单元格内的“列表”容器：一行一个备件，竖向堆叠 */
.stack {
  display: flex;
  flex-direction: column;
  gap: 8px; /* 每个备件行之间的间距 */ 
}

/* 每个备件一行 */
.line {
  display: flex;
  align-items: center;
  min-height: 24px; /* 与小号表格行高协调，可按需调整 */
}

/* 备件名称一行显示，超出省略号 */
.one-line {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 数值列更居中一些（可选） */
.num-col {
  align-items: stretch;
}
.num-col .line {
  justify-content: center;
}

/* 分页粘底的外观（与工单页一致） */
.wo-pager {
  position: sticky;   /* 如不需要粘底，只留下面四行也可以 */
  bottom: 0;
  z-index: 5;
  background: #fff;
  border-top: 1px solid #eef2f6;
  padding: 6px 8px;
  display: flex;
  justify-content: flex-end;
}

</style>
